package xnet.Message
{
	import flash.events.EventDispatcher;
	import flash.utils.ByteArray;
	
	
	import xnet.SocketManager;
	import xnet.core.ObjectUtils;
	import xnet.events.SocketEvent;

	public class MessageFactory extends EventDispatcher
	{
		/**用于存储所有进入工厂的指令集**/
		private static var socketCommands:Array = [];
		
		public function MessageFactory()
		{
			
		}
		/**
		 *注入执行处理函数 
		 */		
		private static var _handler:Function
		public static function set handler(h:Function):void{
			_handler=h;
		}
		
		/**根据传入的byteArray区别类型并将其装入工厂的指令库中**/
		public static function decodeSocketData(byteArray:ByteArray):void
		{
			var iSocketCommand:ISokcetMessage;
			var messageBase:MessageBase
			var copyByteArray:Object = ObjectUtils.copy(byteArray);
			var cmd:int = ByteArray(copyByteArray).readByte();
			/*switch(cmd)
			{
				case Messages.LoginRequest:
					  iSocketCommand = new LoginRequest().decodeSocketData(byteArray);
					break;
			}*/
			messageBase=_handler(cmd,messageBase);
			iSocketCommand=messageBase.decodeSocketData(byteArray);
			socketCommands.push(iSocketCommand);
			SocketManager.instance.dispatchEvent(new SocketEvent(SocketEvent.READY , {cmd:cmd , socketData:byteArray}));
		}
		
		/**根据指令获取相应的指令对象**/
		public static function getCommandByType(cmd:int):ISokcetMessage
		{
			var socketCommand:ISokcetMessage;
			for(var i:int = 0 ; i < socketCommands.length ; i++)
			{
				if(socketCommands[i].type == cmd)
				{
					socketCommand = socketCommands[i];
				}
			}
			return socketCommand;
		}
		
		/**删除指定指令的指令对象**/
		private function delCommand(cmd:int):void
		{
			for(var i:int = 0 ; i < socketCommands.length ; i++)
			{
				if(socketCommands[i].type == cmd)
				{
					socketCommands.splice(i , 1);
				}
			}
		}
	}
}